import loadable from '@loadable/component';
import {loadQuery, } from "react-relay/hooks";
import {Environment} from "relay-runtime";
import InspectMainQuery from "./__generated__/InspectMainQuery.graphql";
import {useContext} from "react";
import UserContext from "../routing/UserContext";
//import queryString from "querystring";
//import IspDetailQuery from "./__generated__/IspDetailQuery.graphql";
import ReportOverviewQuery from "./report/__generated__/ReportOverviewQuery.graphql";
//import {PreloadableConcreteRequest} from "react-relay/relay-hooks/EntryPointTypes";
//import  DetailedGuideQuery  from "./__generated__/DetailedGuideQuery.graphql";
//import DetailMainQuery from "./__generated__/DetailMainQuery.graphql";
//import {DetailReportsQuery} from "./DetailReports";
import {DetailMainQuery} from "./DetailMain";
import TodosMainQuery from "./__generated__/TodosMainQuery.graphql";
import {fromObjToInput} from "../common/tool";

import queryString from "query-string";
/**
 * 多层次的路由器。
 * require（）目录文件无效的不报错，但是路由secondRouter会运行出错加载父文件export失败
 * third layer
 * 如果localStrorage()来存储查询的过滤参数，路由器这里回头读取数据接口的过滤参数：有问题！不可能把URL分享给别人还能看见同一个内容的。
 * /inspect目录页面：负责流转和报告。编制检验报告时间点之前的页面放在/task目录页面去做。
 * 这里loadQuery和XxxMain这类主页面里面的usePreloadedQuery<typeof DetailReportsQuery>(所声称的Query类型名字不一定严格匹配，发请求看loadQuery。
 * myQuery: PreloadedQuery<typeof DetailReportsQuery>避免名字文件配对限制; 只有Relay编译的XxxQuery名字一样的才可以免于重复发起后端请求。
 * 【注意】Query的一致性，路由定义和Main组件里面实际使用Query名字的一致，Relay和编译器不会报错的。
 * 似乎这样 usePreloadedQuery<IspDetailQuery>( DetailReportsQuery,..)都可行的，不一致。
 * */
export default function secondRouter(environment: Environment) {
    //没法用 const {user, setUser} =useContext(UserContext);
    //若不想动态加载数据的话： & 无法利用context!只能上URL参数:来传递过滤器参数给Link/跳转的。
  //React Hook "useContext" is called in function "secondRouter" that is neither a React function component nor a custom React Hook function.
    const qs= queryString.parse(window.location.search);
    const field =qs && !!qs.土建施单;   //json{} URL编码 ?
//左半边算上一级路由内容：跟下一级路由算右半边的页面内容。
  return (
      [
          {
              path: '/inspect',
              exact: true,    //若不设置true:导致后面多个二级路由层次的情况配置的'/inspect'开头的路由失效！
              component: loadable(() => import('./InspectMain')),
              prepare: (params:any) => {
                  //底下这个请求完全可以合并成一个请求包的：从graphql定义入手归并。||{dep:"88909",first:123}
                  //const {dep ,first}=window.history.state?.myQuery;
                  let myobj=sessionStorage['myQuery']&&JSON.parse(sessionStorage['myQuery']);
                  const filt= JSON.parse(sessionStorage['我的检验过滤']??'{}');
                  const idfilt= fromObjToInput(filt,'servu');
                  const srfilt= JSON.parse(sessionStorage['分项报告过滤']??'{}');
                  const sridfilt= fromObjToInput(srfilt,'servu');
                  console.log(`路由InspectMain由params:`,params,"state",window.history.state?.state,"idfilt",idfilt);

                  let vars={
                      status: "",
                      iwhere: { ...idfilt}, after:null, first:8,
                      orderBy: "task.date",
                      swhere: { ...sridfilt},
                      ...myobj
                  };
                  console.log(`loadQuery路由前面:vars=`, vars,"myQuery=",window.history.state?.state?.myQuery);
                  //提前加载数据汇聚graphQL模式：只能在这里就要预备好各个接口函数所有的参数和数值。
                  return {
                      myQuery: loadQuery(
                          environment as any,
                          InspectMainQuery as any,
                          vars,
                          { fetchPolicy: 'store-or-network' },
                      )
                  };
              },
              routes:[
                    //这里设置path: 没意义：会被底下的'/inspect/:ispId'路由条目,给截胡了。
              ],
          },
          {
            path: '/inspect/:ispId',
            component: loadable(() => import('./DetailMain')),
            prepare: (params:any) => {
                  //底下这个请求完全可以合并成一个请求包的：从graphql定义入手归并。||{dep:"88909",first:123}
                  //const {dep ,first}=window.history.state?.myQuery;
                  let myobj=sessionStorage['myQuery']&&JSON.parse(sessionStorage['myQuery']);
                  console.log(`路由inspec简易路11由`,params,"state",window.history.state?.state);

                  let vars={
                      id: params.ispId,
                      status: "1",
                      ...myobj
                  };
                  console.log(`loadQuery路由前面:vars=`, vars,"myQuery=",window.history.state?.state?.myQuery);
                  //提前加载数据汇聚graphQL模式：只能在这里就要预备好各个接口函数所有的参数和数值。
                  return {
                      myQuery: loadQuery(
                          environment as any,
                          DetailMainQuery as any,
                          vars,
                          { fetchPolicy: 'store-or-network' },
                      ),
                  };
            },
            routes:[
                {
                    path: '/inspect/:ispId/addReport',
                    exact: true,
                    component: loadable( () => import('./report/AddReport')),
                    prepare: (params:any) => {
                        return { query: loadQuery(
                                environment as any, DetailMainQuery as any,
                                { id: params.ispId },
                            )
                        };
                    },
                },
                {
                    path: '/inspect/:ispId',
                    exact: true,
                    component: loadable( () => import('./IspDetail')),
                     prepare: (params:any, user: any, nestData: any) => {
                         console.log(`路由历史state点击路由pa22rams:`, params,"nestData", nestData);
                         return {
                             query: loadQuery(
                                 environment as any,
                                 DetailMainQuery as any,
                                 {
                                     id: params.ispId,
                                 },
                                 { fetchPolicy: 'store-or-network' },
                             ),
                         };
                     },
                },
                {
                    path: '/inspect/:ispId/report/:repId',
                    exact: true,
                    component: loadable( () => import('./report/ReportOverview')),
                    prepare: (params:any) => {
                        console.log(`路由历史state27-点击路由params:`, params, window.history.state);
                        return {
                            query: loadQuery(
                                environment as any,
                                ReportOverviewQuery as any,
                                {
                                    id: params.repId,
                                },
                                { fetchPolicy: 'store-or-network' },
                            ),
                        };
                    },
                },

            ],
          },
          {
              path: '/zeebeTodo',
              exact: true,    //若不设置true:导致后面多个二级路由层次的情况配置的'/inspect'开头的路由失效！
              component: loadable(() => import('./TodosMain')),
              prepare: (params:any) => {
                  //底下这个请求完全可以合并成一个请求包的：从graphql定义入手归并。||{dep:"88909",first:123}
                  //const {dep ,first}=window.history.state?.myQuery;
                  let myobj=sessionStorage['myQuery']&&JSON.parse(sessionStorage['myQuery']);
                  console.log(`路由历史secondRouter路由params:`,params,"state",window.history.state?.state);

                  let vars={
                      status: "",
                      where: {sort:"chushi001"}, after:null, first:10,
                      twhere: {},
                      ...myobj
                  };
                  console.log(`loadQuery路由前面:vars=`, vars,"myQuery=",window.history.state?.state?.myQuery);
                  //提前加载数据汇聚graphQL模式：只能在这里就要预备好各个接口函数所有的参数和数值。
                  return {
                      myQuery: loadQuery(
                          environment as any,
                          TodosMainQuery as any,
                          vars,
                          { fetchPolicy: 'store-or-network' },
                      )
                  };
              },
              routes:[ { }, ],
          },
      ]
  );
}

